<template>
  <vxe-table
      resizable
      border
      show-overflow
      show-header-overflow
      show-footer-overflow
      ref="xTable"
      v-loading="loading"
      :height="tableHeight"
      :sort-config="{trigger: 'cell'}"
      :expand-config="{iconOpen: 'vxe-icon-square-minus', iconClose: 'vxe-icon-square-plus'}"
      :scroll-x="{enabled: true, gt: 10}"
      :scroll-y="{enabled: true, gt: 100}">
    <vxe-column type="seq" title="序号"  width="70"/>
    <vxe-column type="expand" title="机台"  >
      <template #default="{ row }">
        <span>{{ row.t_machinename }}</span>
      </template>
      <template #content="{ row }">
        <div class="expand-wrapper">
          <vxe-table
              border
              v-loading="loading2"
              :data="rowData2Map[`${row.t_machinename}#${row.t_batchname}`]">
            <vxe-column type="seq" width="60" title="明细序号"></vxe-column>
            <vxe-column field="t_status" title="状态"  align="center"  sortable/>
            <vxe-column field="t_product_status" title="生产状态" align="center" sortable/>
            <vxe-column field="t_machinename" title="机台"  align="center" sortable/>
            <vxe-column field="t_tubes" title="管数"  align="center" sortable/>
            <vxe-column field="t_dey_number" title="当天机台第几缸" align="center"  sortable/>
            <vxe-column field="t_supcon_time" title="时间"  align="center" sortable/>
            <vxe-column field="t_batchname" title="缸号"  align="center" sortable/>
            <vxe-column field="t_machinestate" title="运行状态"  align="center" sortable/>
            <vxe-column field="t_machinemode" title="在线状态"  align="center" sortable/>
            <vxe-column field="t_dyeing_color_name" title="颜色"  align="center" sortable/>
            <vxe-column field="t_product_code" title="产编"  align="center" sortable/>
            <vxe-column field="t_sub_dyeprogname_01" title="染程1"  align="center" sortable/>
            <vxe-column field="t_sub_dyeprogname_02" title="染程2"  align="center" sortable/>
            <vxe-column field="t_sub_dyeprogname_03" title="染程3"  align="center" sortable/>
            <vxe-column field="t_water_vol1_total_number" title="水量1"  align="right" sortable/>
            <vxe-column field="t_water_vol2_total_number" title="水量2"  align="right" sortable/>
            <vxe-column field="t_water_vol3_total_number" title="水量3"  align="right" sortable/>
            <vxe-column field="t_water_vol4_total_number" title="水量4"  align="right" sortable/>
            <vxe-column field="t_water_vol_total_number" title="总水量"  align="right" sortable/>
            <vxe-column field="t_loading" title="布重量"  align="right" sortable/>
            <vxe-column field="t_loading_rate" title="吨布耗水量(吨/吨布)"  align="right" sortable/>
            <vxe-column field="t_startdatetime" title="开始时间"  align="center" sortable/>
            <vxe-column field="t_enddatetime" title="结束时间"  align="center" sortable/>
            <vxe-column field="t_runtime" title="运行时间"  align="center" sortable/>
          </vxe-table>
        </div>
      </template>
    </vxe-column>
    <vxe-column field="t_batchname" title="缸号" align="center" sortable/>
    <vxe-column field="t_tubes" title="管数" align="center" sortable/>
    <vxe-column field="t_inechart" title="折线图" >
      <template #default="{ row }">
        <vxe-button @click="buttonClick(row)">折线图</vxe-button>
      </template>
    </vxe-column>
  </vxe-table>
</template>

<script>
import {getSupconDatasD, getSupconDatasH} from '@/exclude-folder/services/DataService1'

export default {
  name: 'MyComponent',
  data () {
    return {
      loading: true,
      rowData2Map: {}, // 用于存储每行对应的tableData2[t_machinename+t_batchname]
      tableHeight: 0 // 响应式属性，用于存储表格高度
    }
  },
  async mounted () {
    document.title = '中控数据看板明细';
    this.setWindowHeight(); // 设置初始高度
    window.addEventListener('resize', this.setWindowHeight); // 监听窗口大小变化
    // 调用一个异步函数来获取数据大小
    this.fetchDataAndLoadTable();
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.setWindowHeight); // 组件销毁前移除监听器
  },
  methods: {
    async handleClick(row) {

      // row.t_machinename
      let machinename = "";
      let batchname = "";
      for (let key in row) {
        if (key === "t_machinename") {
          machinename = row[key];
        } else if (key === "t_batchname") {
          batchname = row[key];
        }
      }
      machinename = encodeURIComponent(machinename);
      batchname = encodeURIComponent(batchname);
      const url_href = window.location.href;
      const baseUrl = url_href.split('#/')[0];
      // 在新标签页中打开
      let url = `${baseUrl}#/echartsline?machinename=${machinename}&batchname=${batchname}`;
      window.open(url, '_blank'); // 在新标签页中打开
    },
    async fetchDataAndLoadTable() {
      try {
        const res = await getSupconDatasH(); // 假设这是获取实际数据长度的函数
        // 等待 DOM 更新后再加载数据
        this.$nextTick(() => {
          const $table = this.$refs.xTable;

          this.mockList(res).then(data => {
            if ($table) {
              $table.loadData(data);
            }
          });
        });

        this.loading = false;
      } catch (error) {
        this.loading = false;
        console.error('Error fetching data:', error);
        // 错误处理...
      }
    },
    async loadTableData2(t_machinename,t_batchname) {
      // 假设获取tableData2的接口地址是'api/tableData2/:id'
      try {
        const res2 = await getSupconDatasD(t_machinename,t_batchname);
        const key = `${t_machinename}#${t_batchname}`;

        // 检查 key 是否已经在 rowData2Map 中，如果没有则初始化为空数组
        if (!this.rowData2Map[key]) {
          this.rowData2Map[key] = [];
        }

        const size = res2.length;
        for (let index = 0; index < size; index++) {
          let startdatetime = res2[index].t_startdatetime;
          let machinestate = res2[index].t_machinestate;
          let machinemode = res2[index].t_machinemode;
          let loading_rate = res2[index].t_loading_rate;
          let product_status = "完成";
          let err_status = "中控正常";
          if (startdatetime === undefined || startdatetime === null || startdatetime === ''){
            product_status = "未完成";
          }
          if (machinestate === '单机'){
            err_status = "单机运行异常";
            if (machinemode === '停止'){
              err_status = "单机停止异常";
            }
          }else if (machinemode === '中央' && machinemode === '停止'){
            err_status = "中央停止异常";
          }
          if (loading_rate > '75'){
            // err_status = "耗水异常(超75%)";
            if(err_status.length>0){
              err_status += ";耗水异常(超75%)";
            }else{
              err_status = "耗水异常(超75%)";
            }
          }
          this.rowData2Map[key].push({
            t_machinename: res2[index].t_machinename,
            t_tubes: res2[index].t_tubes,
            t_dey_number: res2[index].t_dey_number,
            t_supcon_time: res2[index].t_supcon_time,
            t_batchname: res2[index].t_batchname,
            t_machinestate: res2[index].t_machinestate,
            t_machinemode: res2[index].t_machinemode,
            t_dyeing_color_name: res2[index].t_dyeing_color_name,
            t_product_code: res2[index].t_product_code,
            t_sub_dyeprogname_01: res2[index].t_sub_dyeprogname_01,
            t_sub_dyeprogname_02: res2[index].t_sub_dyeprogname_02,
            t_sub_dyeprogname_03: res2[index].t_sub_dyeprogname_03,
            t_water_vol1_total_number: res2[index].t_water_vol1_total_number,
            t_water_vol2_total_number: res2[index].t_water_vol2_total_number,
            t_water_vol3_total_number: res2[index].t_water_vol3_total_number,
            t_water_vol4_total_number: res2[index].t_water_vol4_total_number,
            t_water_vol_total_number: res2[index].t_water_vol_total_number,
            t_loading: res2[index].t_loading,
            t_loading_rate: loading_rate,
            t_startdatetime: res2[index].t_startdatetime,
            t_enddatetime: res2[index].t_enddatetime,
            t_runtime: res2[index].t_runtime,
            t_status: err_status,
            t_product_status: product_status
          });
        }
        this.loading2 = false;
      } catch (error) {
        this.loading = false;
        console.error(`获取t_machinename和t_batchname为${t_machinename}#${t_batchname}的tableData2失败:`, error);
      }
    },
    mockList (res) {
      const size = res.length;
      return new Promise(resolve => {
        const list = []
        for (let index = 0; index < size; index++) {
          const machinename = res[index].t_machinename;
          const batchname = res[index].t_batchname;
          list.push({
            t_machinename: machinename,
            t_batchname: batchname,
            t_tubes: res[index].t_tubes,
          })
          this.loadTableData2(machinename,batchname);
        }
        resolve(list)
      })
    },
    async buttonClick(row) {
      let machinename = "";
      let batchname = "";
      for (let key in row) {
        if (key === "t_machinename") {
          machinename = row[key];
        } else if (key === "t_batchname") {
          batchname = row[key];
        }
      }
      machinename = encodeURIComponent(machinename);
      batchname = encodeURIComponent(batchname);
      const url_href = window.location.href;
      const baseUrl = url_href.split('#/')[0];
      // 在新标签页中打开
      let url = `${baseUrl}#/echartsline?machinename=${machinename}&batchname=${batchname}`;
      window.open(url, '_blank'); // 在新标签页中打开
    },
    setWindowHeight() {
      // 计算可用高度，这里只是一个示例，你可能需要根据你的布局进行调整
      const windowHeight = window.innerHeight;
      // 假设你要留给表格之外的内容（如页眉、页脚等）100px的高度
      this.tableHeight = windowHeight - 60;
    },
    cellStyle ({ row, column }) {
      if (column.field === 't_product_status') {
        if (row.t_product_status == '未完成') {
          return {
            backgroundColor: '#d45813',
            color: '#ffffff' // 设置字体颜色为白色
          }
        } else{
          return {
            backgroundColor: '#fffcfc',
            color: '#000000' // 设置字体颜色为黑色
          }
        }
      }
      if (column.field === 't_status') {
        let status = row.t_status;
        if (status == '单机运行异常') {
          return {
            backgroundColor: '#D45813FF',
            color: '#ffffff' // 设置字体颜色为白色
          }
        }else if (status == '单机停止异常') {
          return {
            backgroundColor: '#d45813',
            color: '#ffffff' // 设置字体颜色为白色
          }
        }else if (status === '中央停止异常'){
          return {
            backgroundColor: '#C79E88FF',
            color: '#ffffff' // 设置字体颜色为白色
          }
        }else if (status.includes('耗水异常(超75%)')){
          return {
            backgroundColor: '#e07810',
            color: '#ffffff' // 设置字体颜色为白色
          }
        }else{
          return {
            backgroundColor: '#fffcfc',
            color: '#000000' // 设置字体颜色为黑色
          }
        }
      }
      // 如果不是特殊列，则返回默认的样式对象
      return {};
    },
  }
}
</script>

<style scoped>
.vxe-button {
  /* 按钮的默认样式 */
  padding: 5px 10px;
  background-color: #02D1FFFF;
  color: #fff;
  border: none;
  cursor: pointer;
}
</style>
